package com.ljc.cjgl.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import org.abyss.data.specifications.Rule;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ljc.cjgl.custom.TablePageable;
import com.ljc.cjgl.custom.TableResult;
import com.ljc.cjgl.entitiy.TbClass;
import com.ljc.cjgl.form.ClassForm;
import com.ljc.cjgl.service.ClassService;

@Controller
@RequestMapping(value="/banji")
public class ClassController {
	
	@Autowired
	private ClassService service;
	
	@RequestMapping(value="/manage")
	public String manage() {
		return "banji/manage";
	}
	
	@RequestMapping(value="/page")
	@ResponseBody
	public Object page(TablePageable pageable, ClassForm form) {
		PageRequest pageRequest = pageable.bulidPageRequest();
		String name = form.getName();
		String manager = form.getManager();
		String search = form.getSearch();
		HashSet<Rule> rules=new HashSet<>();
		if(StringUtils.hasText(name)) {
			rules.add(Rule.property("name").contain(name));
		}
		if(StringUtils.hasText(manager)) {
			rules.add(Rule.property("manager").contain(manager));
		}
		if(StringUtils.hasText(search)) {
			HashSet<Rule> rules2=new HashSet<>();
			rules2.add(Rule.property("name").contain(search));
			rules2.add(Rule.property("manager").contain(search));
			rules.add(Rule.or(rules2));
		}
		Specification<TbClass> spec = Rule.and(rules).toSpecification();
		Page<TbClass>page= service.findAll(spec,pageRequest);
		return TableResult.bulidPageResult(page);
	}
	
	@RequestMapping("/edit")
	public String edit(Integer id,ModelMap map) {
		TbClass model=new TbClass();
		if(id!=null) {
			model=service.findById(id);
		}
		map.put("model", model);
		return "banji/edit";
		
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public Object save(ClassForm form) {
		TbClass model=new TbClass();
		BeanUtils.copyProperties(form, model);
		service.save(model);
		return TableResult.bulidResult(true, "数据保存成功");
	}
	
	@RequestMapping("/delete")
	@ResponseBody
	public Object delete(@RequestBody List<TbClass> bjs) {
		Boolean flag=service.delete(bjs);
		HashMap<String, Object> result=new HashMap<>();
		if(flag) {
			result.put("success", true);
			result.put("msg", "数据删除成功");
		}else {
			result.put("success", false);
			result.put("msg", "数据删除失败，请先删除下级数据");
		}
		return result;
	}
}
